package com.nidu.demo.oauth2.ability;

import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.oauth2.gateway.OAuth2CodeGateway;
import com.nidu.demo.oauth2.model.OAuth2Client;
import com.nidu.demo.oauth2.model.OAuth2Code;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Component
@RequiredArgsConstructor
public class OAuth2CodeDomainService {

    private final OAuth2CodeGateway gateway;

    @Transactional
    public OAuth2Code validateCode(String code, Long clientId, String redirectUri) {
        OAuth2Code oAuth2Code = gateway.getByCode(code);
        if (oAuth2Code == null){
            throw new BizException(ErrorCodeConstants.OAUTH2_CODE_NOT_FOUND.getCode(), ErrorCodeConstants.OAUTH2_CODE_NOT_FOUND.getMessage());
        }
        oAuth2Code.isDeleted();
        if(!oAuth2Code.getClientId().equals(clientId)) {
            throw new BizException(ErrorCodeConstants.OAUTH2_CODE_CLIENT_FAIL.getCode(), ErrorCodeConstants.OAUTH2_CODE_CLIENT_FAIL.getMessage());
        }
        if (!StrUtil.isEmpty(redirectUri) && !redirectUri.equals(oAuth2Code.getRedirectUri())) {
            throw new BizException(ErrorCodeConstants.OAUTH2_CODE_REDIRECT_URL_FAIL.getCode(), ErrorCodeConstants.OAUTH2_CODE_REDIRECT_URL_FAIL.getMessage());
        }
        if(oAuth2Code.isExpired()){
            gateway.deleteById(oAuth2Code.getId());
        }
        return oAuth2Code;
    }

    public OAuth2Code createCode(Long userId, Integer value, OAuth2Client client, List<String> scopes, String redirectUri) {
        OAuth2Code oAuth2Code = OAuth2Code.create(userId, value, client.getId(), scopes,
                LocalDateTime.now().plusSeconds(client.getRefreshTokenValiditySeconds()), redirectUri);
        return this.gateway.create(oAuth2Code);
    }
}
